import { getToken, removeToken, setToken } from "@/utils/auth";
import api from "@/api/api";
import { isZxcxAPP, zxcxStartLocation } from "@/utils/zxcxWebkits";
import router from "@/router";
import { update } from "lodash-es";

const getDefaultState = () => {
  return {
    token: getToken(),
    userData: JSON.parse(sessionStorage.getItem("userData")) || {},
    carList: JSON.parse(sessionStorage.getItem("carList")) || [],
    locationInfo: JSON.parse(sessionStorage.getItem("location")) || {},
    addressList: JSON.parse(sessionStorage.getItem("address")) || [],
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_USER: (state, data) => {
    state.userData = data;
    sessionStorage.setItem("userData", JSON.stringify(data));
  },
  SET_CAR: (state, data) => {
    state.carList = data;
    sessionStorage.setItem("carList", JSON.stringify(data));
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
    setToken(token);
  },
  SET_LOCATION: (state, data) => {
    state.locationInfo = data;
    sessionStorage.setItem("location", JSON.stringify(data));
  },
  SET_ADDRESS: (state, data) => {
    state.addressList = data;
    sessionStorage.setItem("address", JSON.stringify(data));
  },
};

const actions = {
  // get user info
  async getInfo({ commit, state }, userId) {
    if (Object.keys(state.userData).length > 0) {
      return state.userData;
    } else {
      let res = await api.login({ userId }).catch(() => {
        router.replace({
          path: "/404",
        });
      });
      if (!res.token) {
        router.replace({
          path: "/404",
        });
      }
      commit("SET_TOKEN", res.token);
      commit("SET_USER", {
        avatar: res.avatar,
        phone: res.phone,
        userName: res.userName,
        role: res.roles,
        id: res.userId,
        isVip: res.memberFlag,
        vip_start: res?.memberStart,
        vip_end: res?.memberEnd,
      });
      let res2 = await api.getCarList({});
      commit("SET_CAR", res2.data);
      commit("common/SET_CURRENT_CAR_INDEX", 0, { root: true });
      if (isZxcxAPP()) {
        let loc = await zxcxStartLocation().catch((err) => {
          console.log(err);
        });
        commit("SET_LOCATION", loc);
      }
    }
  },
  async updateUserInfo({ commit }, userId) {
    let res = await api.login({ userId }).catch(() => {
      router.replace({
        path: "/404",
      });
    });
    if (!res.token) {
      router.replace({
        path: "/404",
      });
    }
    commit("SET_TOKEN", res.token);
    commit("SET_USER", {
      avatar: res.avatar,
      phone: res.phone,
      userName: res.userName,
      role: res.roles,
      id: res.userId,
      isVip: res.memberFlag,
      vip_start: res?.memberStart,
      vip_end: res?.memberEnd,
    });
  },
  getToken({ commit }, params) {
    return new Promise((resolve, reject) => {
      commit("SET_TOKEN", params);
    });
  },
  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
